#include <iostream>
#include "AreaMap.h"

// create a heightmap with medium height values
AreaMap::AreaMap(int map_size, int quad_size)
{
	map_width = map_size;
	map_depth = map_size;
	this->quad_size = quad_size;
	map_data_size = (map_width+1)*(map_depth+1);
	std::cout<<"map size="<<map_data_size<<std::endl;
	map_data = new byte[map_data_size];
	
	for(int i = 0; i < map_data_size; i++)
		map_data[i] = 128;
	
	glNewList(map_list,GL_COMPILE); //compile the list
	construct();
	glEndList(); //end the list
}

int AreaMap::heightAt(int x, int z)
{
	if (x + z*map_width < map_data_size)
		return map_data[x + z*map_width];
	else
		return 0;
}

void AreaMap::vertexColour(int height)
{
	float colour = height / 256.0f;
	glColor3f(colour, 100,0);
}

void AreaMap::render()
{
	glCallList(map_list); //call the list
}

void AreaMap::construct()
{
	int x, y, z; // ints to store the values of each vertex

	glBegin(GL_QUADS);							
	for (int i = 0; i < map_width; i += quad_size) {
		for (int j = 0; j < map_depth; j += quad_size) {

			// get the coordinates for each vertex in turn
			int x_extend = 0, z_extend = 0;
			for (int k = 0; k < 2; k++) {

				if (k > 0)
					x_extend = quad_size;

				for (int l = 0; l < 2; l++) {

					if (k + l > 0 && k + l < 2)
						z_extend = quad_size;
					else
						z_extend = 0;

					// get the current vertex coordinates
					x = i + x_extend;							
					z = j + z_extend;							
					y = heightAt(x,z);	

					vertexColour(y);// set the colour value according to height
					glVertex3i(x, y, z);
				}
			}
		}
	}
	glEnd();
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);					// Reset The Color
}


AreaMap::~AreaMap(void)
{
	delete[] map_data;
}
